<template>
    <el-form :model="formData" label-width="120px">
    <el-form-item label="品类名称">
      <el-input v-model="formData.name" />
    </el-form-item>
    <el-form-item label="图片">
      <Tuku v-model="formData.img"></Tuku>
    </el-form-item>
     <el-form-item label="父类">
            <el-tree-select v-model="formData.parentId" :data="data" :render-after-expand="false" />
      </el-form-item>
    <el-form-item label="排序">
      <el-input-number v-model="formData.sort" :min="1" :max="100" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import Tuku   from '@/components/Tuku.vue'
import { categoryApi } from '@/api'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from "vue-router";
//路由
const route = useRoute(); //用于获取当前页面的参数
const router = useRouter(); //用于页面的跳转

//表单数据
const formData = reactive({
  id:"",
  name: '',
  img:"",
  sort:0,
  parentId:""
})
//父级分类数据
const data=ref([{value:0,label:"一级分类"}])

//钩子函数
onMounted(()=>{
  //查询一级分类列表
  getCategoryList()
  //数据回显
  getCategoryById()
})

//根据id查询品类的数据
const getCategoryById=()=>{
  categoryApi.selectById.call({id:route.query.id}).then((res:any)=>{
    console.log(res)
    formData.id=res.id
    formData.name=res.name
    formData.img=res.img
    formData.sort=res.sort
    formData.parentId=res.parentId
  })
}
//查询分类列表
const getCategoryList=()=>{
  categoryApi.select.call({parentId:0}).then((res:any)=>{
    res.forEach(item => {
            item.value = item.id
            item.label = item.name
        });
    data.value = data.value.concat(res)
  })
}
//更新品类的api
const updateCategory=()=>{
  categoryApi.update.call(formData).then((res:any)=>{
    ElMessage.success("修改成功")
    
  })
}
//提交表单
const onSubmit = () => {
  //调用接口更新品类
  updateCategory()
  router.push({name:"category-list"})
}
</script>